using System;
using System.Collections.Generic;
using System.Linq;

namespace SilverAmp.Common.DecoupledEvents
{

    /// <summary>
    /// Aggregator to access the decoupled eventing system. Decoupled means there will be no refecences 
    /// between event and subscriber. The publisher of an event doesn't need to know anything about the 
    /// subscriber. 
    /// </summary>
    public class DecoupledEventAggregator
    {
        private readonly List<DecoupledEventBase> _events;

        private DecoupledEventAggregator()
        {
            _events=new List<DecoupledEventBase>();
        }

        private static DecoupledEventAggregator _self = null;
        private static readonly object Lockhelper = new object();

        /// <summary>
        /// Gets the instance of the EventAggregator.
        /// </summary>
        /// <returns></returns>
        public static DecoupledEventAggregator GetInstance()
        {
            lock (Lockhelper)
            {
                if (_self == null) 
                    _self = new DecoupledEventAggregator();
            
                return _self;
            }
        }

        /// <summary>
        /// Gets the event to subscribe to or publish.
        /// </summary>
        /// <typeparam name="T">The type of event</typeparam>
        /// <returns></returns>
        public T GetEvent<T>() where T : DecoupledEventBase
        {
            var eventInstance = _events.FirstOrDefault(evt => evt.GetType() == typeof(T)) as T;
            if (eventInstance == null)
            {
                eventInstance = Activator.CreateInstance<T>();
                _events.Add(eventInstance);
            }
            return eventInstance;
                   
        }
    }
}